package com.doufeng.order.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doufeng.common.result.Result;
import com.doufeng.order.dto.OrderDTO;
import com.doufeng.order.dto.OrderUpdateDTO;
import com.doufeng.order.entity.Order;
import com.doufeng.order.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    /**
     * 创建订单
     *
     * @param dto 订单信息
     * @return Result<Order>
     */
    @PostMapping
    public Result<Order> create(@RequestBody OrderDTO dto) {
        Order order = new Order();
        BeanUtils.copyProperties(dto, order);
        boolean saved = orderService.saveOrder(order);
        if (saved) {
            return Result.success(order);
        }
        return Result.fail(500, "创建订单失败");
    }

    /**
     * 根据ID获取订单
     *
     * @param id 订单ID
     * @return Result<Order>
     */
    @GetMapping("/{id}")
    public Result<Order> getById(@PathVariable("id") Long id) {
        Order order = orderService.getById(id);
        if (order != null) {
            return Result.success(order);
        }
        return Result.fail(404, "订单不存在");
    }

    /**
     * 更新订单
     *
     * @param id    订单ID
     * @param dto 订单信息
     * @return Result<Order>
     */
    @PutMapping("/{id}")
    public Result<Order> update(@PathVariable("id") Long id, @RequestBody OrderUpdateDTO dto) {
        Order order = orderService.getById(id);
        if (order == null) {
            return Result.fail(404, "订单不存在");
        }
        if (dto.getStatus() != null&& order.getStatus().equals(1)) {
            return Result.fail(409, "订单已支付");
        }

        // 只更新传入的字段
        if (dto.getServiceType() != null) {
            order.setServiceType(dto.getServiceType());
        }
        if (dto.getStatus() != null) {
            order.setStatus(dto.getStatus());
        }
        if (dto.getAmount() != null) {
            order.setAmount(dto.getAmount());
        }
        if (dto.getAddress() != null) {
            order.setAddress(dto.getAddress());
        }
        if (dto.getLng() != null) {
            order.setLng(dto.getLng());
        }
        if (dto.getLat() != null) {
            order.setLat(dto.getLat());
        }
        
        boolean updated = orderService.updateById(order);
        if (updated) {
            return Result.success(order);
        }
        return Result.fail(500, "更新订单失败");
    }

    /**
     * 删除订单
     *
     * @param id 订单ID
     * @return Result<String>
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable("id") Long id) {
        boolean removed = orderService.removeById(id);
        if (removed) {
            return Result.success("删除成功");
        }
        return Result.fail(500, "删除订单失败");
    }
    
    /**
     * 订单支付成功回调接口
     *
     * @param orderNo 订单编号
     * @return Result<String>
     */
    @PostMapping("/pay/success")
    public Result<String> paySuccess(@RequestParam("orderNo") String orderNo) {
        // 参数校验
        if (orderNo == null || orderNo.trim().isEmpty()) {
            return Result.fail(400, "订单编号不能为空");
        }
        
        try {
            orderService.paySuccess(orderNo.trim());
            return Result.success("支付处理成功");
        } catch (IllegalArgumentException e) {
            return Result.fail(400, "非法参数：" + e.getMessage());
        } catch (IllegalStateException e) {
            return Result.fail(409, "状态错误：" + e.getMessage());
        } catch (Exception e) {
            // 记录异常信息，便于排查问题
            return Result.fail(500, "支付处理失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询订单
     *
     * @param page 页码
     * @param size 每页大小
     * @return Result<Page < Order>>
     */
    @GetMapping("/page")
    public Result<Page<Order>> page(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                    @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Page<Order> pageResult = orderService.page(new Page<>(page, size),
                new LambdaQueryWrapper<Order>().eq(Order::getDeleted, 0));
        return Result.success(pageResult);
    }
}